<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 获取全局属性
const { proxy } = getCurrentInstance()

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增广告主')
const formMode = ref('add') // add or edit

// 表单数据
const form = ref({
  advertiserId: '',
  companyName: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: ''
})

// 表单规则
const rules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取广告主列表
const getAdvertisersList = async () => {
  loading.value = true;
  try {
    const result = await request.get('/advertisers', {
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize
      }
    });

    tableData.value = result.data.records;
    pagination.value.total = result.data.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    tableData.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理页码改变
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  getAdvertisersList();
};

// 处理每页条数改变
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  getAdvertisersList();
};

// 打开新增对话框
const handleAdd = () => {
  formMode.value = 'add'
  dialogTitle.value = '新增广告主'
  form.value = {
    advertiserId: '',
    companyName: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  formMode.value = 'edit'
  dialogTitle.value = '编辑广告主'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除广告主
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该广告主吗？删除后相关的广告计划也会被删除！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/advertisers/${row.advertiserId}`);
      ElMessage.success('删除成功');
      // 如果当前页只有一条数据，且不是第一页，则删除后跳转到上一页
      if (tableData.value.length === 1 && pagination.value.currentPage > 1) {
        pagination.value.currentPage--;
      }
      getAdvertisersList();
    } catch (error) {
      // 错误已经被 request 拦截器处理
      console.error('删除失败:', error);
    }
  }).catch(() => {
    // 用户取消删除操作
  });
}

// 提交表单
const handleSubmit = async () => {
  try {
    const method = formMode.value === 'add' ? 'post' : 'put';
    const url = formMode.value === 'add'
      ? '/advertisers'
      : `/advertisers/${form.value.advertiserId}`;

    await request[method](url, form.value);
    ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功');
    dialogVisible.value = false;
    getAdvertisersList();
  } catch (error) {
    // 错误已经被 request 拦截器处理
    console.error(formMode.value === 'add' ? '新增失败:' : '编辑失败:', error);
  }
}

onMounted(() => {
  getAdvertisersList()
})
</script>

<template>
  <div class="advertisers-manage">
    <div class="header">
      <h2>广告主管理</h2>
      <el-button type="primary" @click="handleAdd">新增广告主</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column prop="advertiserId" label="ID" width="80" />
      <el-table-column prop="companyName" label="公司名称" />
      <el-table-column prop="contactPerson" label="联系人" />
      <el-table-column prop="contactPhone" label="联系电话" />
      <el-table-column prop="contactEmail" label="联系邮箱" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.advertisers-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
